<?php

namespace app\admin\controller;

use app\api\model\UserNoble;
use app\api\model\UserPunish;
use think\Db;
use think\Cache;
use think\Session;

class Admin extends Common
{
    public function index()
    {
        $type = input('type/d',0);
        $this->assign('type', $type);

        $admin_type = Db::name('admin_type')->field('id,title')->select();
        $this->assign('admintype', $admin_type);

        $where = [];

        if ($type) {
            $where['a.type'] = $type;
        }

        $data = Db::name('admin a')
            ->join('admin_type b', 'a.type = b.id')
            ->where($where)
            ->field('a.id,a.type,a.name,a.city,b.title,a.create_time,a.create_ip,a.update_time,a.update_ip,a.hide,a.sort')
            ->order('sort desc, id asc')
            ->paginate();

        $this->assign('data', $data);

        return $this->fetch();
    }

    public function add()
    {
        $id = input("id");

        $admin_type = Db::name('admin_type')->field('id,title')->select();
        $this->assign('admintype', $admin_type);

        if (request()->isAjax()) {
            $post = input('post.');
            $validate = validate('Admin');
            $array = ['type' => $post['type'], 'hide' => $post['hide']];
            if (!$post['name']) {
                return ['err' => '请输入账户'];
            }
            if ($validate->check($post)) {
                if ($post['password'] != $post['password2']) {
                    return ['err' => '密码和确认密码不一致'];
                }
                $time = time();
                $ip = _ip();
                if ($id) {
                    if (!$post['password']) {
                        $password = db('admin')->where('id', $id)->value('password');
                    } else {
                        $password = md5($post['password']);
                    }
                } else {
                    $password = md5($post['password']);
                }
                $dbdata = ['name' => $post['name'], 'password' => $password, 'update_time' => $time, 'update_ip' => $ip, 'sort'=>$post['sort']??0];
                $dbdata = array_merge($array, $dbdata);
                if (!$id) {   // 添加数据
                    $title = db('admin_type')->where('id', $post['type'])->value('title');
                    if ($title == '城市代理') {
                        $dbdata['city'] = trim($post['city']);
                        if (!$dbdata['city']) {
                            return ['err' => '代理城市未填写'];
                        }
                    }
                    $namebd = db('admin')->where('name', $post['name'])->find();
                    if ($namebd) {
                        return ['err' => '账户已存在'];
                    }
                    if (!$post['password']) {
                        return ['err' => '密码不可为空'];
                    }
                    $dbdatas = ['create_time' => $time, 'create_ip' => $ip];
                    $dbdata = array_merge($dbdatas, $dbdata);
                    $db = db('admin')->insert($dbdata);
                    if ($db) {
                        $data = ['ret' => '添加成功'];
                    } else {
                        $data = ['err' => '添加失败'];
                    }
                } else {      //修改数据
                    if ($id == 1) {
                        $safe_pass = input('safe_pass');
                        if ($safe_pass) {
                            $safe_pass = password_hash($safe_pass, PASSWORD_DEFAULT);
                        }
                        $dbdata = ['name' => $post['name'], 'password' => $password, 'safe_pass' => $safe_pass];
                    }
                    $title = db('admin_type')->where('id', $post['type'])->value('title');
                    if ($title == '城市代理') {
                        $dbdata['city'] = trim($post['city']);
                        if (!$dbdata['city']) {
                            return ['err' => '代理城市未填写'];
                        }
                    } else {
                        $dbdata['city'] = '';
                    }

                    $db = db('admin')->where('id', $id)->update($dbdata);
                    if ($db) {
                        $data = ['ret' => '修改成功'];
                    } else {
                        $data = ['err' => '修改失败'];
                    }
                }
            } else {
                $data = ["err" => $validate->getError()];
            }
        } else {
            if ($id) {
                // $name=db('admin')->where('id',$id)->find();
                $name = db('admin')
                    ->alias('t1')
                    ->field('t1.*,t2.title')
                    ->join('admin_type t2', 't2.id = t1.type')
                    ->where('t1.id', $id)
                    ->find();

                if ($name) {
                    $this->assign('name', $name);
                } else {
                    $data = ['err' => 'id参数错误'];
                }
            }
            $data = $this->fetch();
        }
        return $data;
    }


    //删除管理员账户
    public function del()
    {
        if (request()->isAjax()) {

            $id = input('id');
            if ($id == 1) {
                $data = ['err' => '账户禁止删除'];
            } else {
                if (input('?id')) {
                    $db = db('admin')->delete($id);
                    if ($db) {
                        $data = ['ret' => '删除成功'];
                    } else {
                        $data = ['err' => '删除失败' . $db];
                    }
                } else {
                    $data = ['err' => 'id参数错误'];
                }
            }

        } else {
            $data = ['err' => '提交参数错误'];
        }
        return $data;
    }


    //权限与类型
    public function type()
    {
        $data = db('admin_type')->select();
        $this->assign('data', $data);
        return $this->fetch();
    }


    // 添加权限类型
    public function typeadd()
    {
        $id = input("id");
        $t = db('category')->where('tid', 0)->order('des desc,id asc')->select();
        $html = '';
        foreach ($t as $k => $v) {
            $html .= '<h5>' . $v['title'] . '</h5>';
            // $t2 = db('category')->where('tid', $v['id'])->where(['hideleft' => ['neq', 0]])->order('des desc,id asc')->select();
            $t2 = db('category')->where('tid', $v['id'])->order('des desc,id asc')->select();
            if ($t2) {
                foreach ($t2 as $v2) {
                    $html .= '<div class="form-group">';
                    $html .= '<label class="col-sm-2 control-label">' . $v2['title'] . '：</label>';
                    $html .= '<div class="col-sm-10">';
                    $html .= '<div class="radio i-checks">';
                    if ($v2['controller'] && $v2['function']) {
                        $checked = '';
                        if ($id) {
                            $checkeddb = db('admin_type')->where('id', $id)->value('data');
                            if ($checkeddb) {
                                foreach (json_decode($checkeddb) as $cv) {
                                    if ($cv == $v2['id']) {
                                        $checked = 'checked';
                                        break;
                                    }
                                }
                            } else {
                                return ['err' => 'id参数对应权限数据不存在'];
                            }
                        }
                        $html .= '<label class="col-md-3"><input type="checkbox" ' . $checked . ' value="' . $v2['id'] . '" name="data[]">' . $v2['title'] . '</label>';
                        $t3 = db('category')->where('tid', $v2['id'])->order('des desc,id asc')->select();
                        if ($t3) {
                            foreach ($t3 as $v3) {
                                $checked = '';
                                if ($id) {
                                    $checkeddb = db('admin_type')->where('id', $id)->value('data');
                                    if ($checkeddb) {
                                        foreach (json_decode($checkeddb) as $cv) {
                                            if ($cv == $v3['id']) {
                                                $checked = 'checked';
                                                break;
                                            }
                                        }
                                    } else {
                                        return ['err' => 'id参数对应权限数据不存在'];
                                    }
                                }
                                $html .= '<label class="col-md-3"><input type="checkbox" ' . $checked . ' value="' . $v3['id'] . '" name="data[]">' . $v3['title'] . '</label>';

                                $t4 = db('category')->where('tid', $v3['id'])->order('des desc,id asc')->select();
                                if ($t4) {
                                    foreach ($t4 as $v4) {
                                        $checked = '';
                                        if ($id) {
                                            foreach (json_decode($checkeddb) as $cv) {
                                                if ($cv == $v4['id']) {
                                                    $checked = 'checked';
                                                    break;
                                                }
                                            }
                                        }
                                        $html .= '<label class="col-md-3"><input type="checkbox" ' . $checked . ' value="' . $v4['id'] . '" name="data[]">' . $v4['title'] . '</label>';
                                    }
                                }
                            }
                        }
                    } else {
                        $t3 = db('category')->where('tid', $v2['id'])->order('des desc,id asc')->select();
                        if ($t3) {
                            foreach ($t3 as $v3) {
                                $checked = '';
                                if ($id) {
                                    $checkeddb = db('admin_type')->where('id', $id)->value('data');
                                    if ($checkeddb) {
                                        foreach (json_decode($checkeddb) as $cv) {
                                            if ($cv == $v3['id']) {
                                                $checked = 'checked';
                                                break;
                                            }
                                        }
                                    } else {
                                        return ['err' => 'id参数对应权限数据不存在'];
                                    }
                                }
                                $html .= '<label class="col-md-3"><input type="checkbox" ' . $checked . ' value="' . $v3['id'] . '" name="data[]">' . $v3['title'] . '</label>';

                                
                                $t4 = db('category')->where('tid', $v3['id'])->order('des desc,id asc')->select();
                                if ($t4) {
                                    foreach ($t4 as $v4) {
                                        $checked = '';
                                        if ($id) {
                                            foreach (json_decode($checkeddb) as $cv) {
                                                if ($cv == $v4['id']) {
                                                    $checked = 'checked';
                                                    break;
                                                }
                                            }
                                        }
                                        $html .= '<label class="col-md-3"><input type="checkbox" ' . $checked . ' value="' . $v4['id'] . '" name="data[]">' . $v4['title'] . '</label>';
                                    }
                                }
                            }
                        }
                    }

                    $html .= '</div></div></div>';
                }
            }
        }
        $this->assign('category', $html);
        if (request()->isAjax()) {

            $post = input('post.');;
            $title = $post['title'];
            if (!input('?post.data')) {
                $dataname = false;
            } else {
                $dataname = $post['data'];
            }
            if ($title) {
                if ($dataname) {
                    $array = ['title' => $title, 'data' => json_encode($dataname)];
                    if (!$id) {   // 添加数据
                        $titledb = db('admin_type')->where('title', $title)->find();
                        if ($titledb) {
                            $data = ['err' => '名称已存在'];
                        } else {
                            $db = db('admin_type')->insert($array);
                            if ($db) {
                                $data = ['ret' => '添加成功'];
                            } else {
                                $data = ['err' => '添加失败'];
                            }
                        }
                    } else {      //修改数据
                        if ($id == 1) {
                            $array = ['title' => $title];
                            $db = db('admin_type')->where('id', $id)->update($array);
                        } else {
                            $db = db('admin_type')->where('id', $id)->update($array);
                        }
                        if ($db) {
                            $data = ['ret' => '修改成功'];
                        } else {
                            $data = ['err' => '修改失败'];
                        }
                    }
                } else {
                    $data = ['err' => '最少选一个权限'];
                }
            } else {
                $data = ['err' => '类型名称不可为空'];
            }
        } else {
            if ($id) {
                $name = db('admin_type')->where('id', $id)->find();
                if ($name) {
                    $this->assign('name', $name);
                } else {
                    $data = ['err' => 'id参数错误'];
                }
            }
            $data = $this->fetch();
        }
        return $data;
    }


    //删除权限与类型
    public function typeDel()
    {
        if (request()->isAjax()) {

            $id = input('id');
            if ($id == 1) {
                $data = ['err' => '超级管理员禁止删除'];
            } else {
                if (input('?id')) {
                    $admin = db('admin')->where('type', $id)->find();
                    if (!$admin) {
                        $db = db('admin_type')->delete($id);
                        if ($db) {
                            $data = ['ret' => '删除成功'];
                        } else {
                            $data = ['err' => '删除失败'];
                        }
                    } else {
                        $data = ['err' => '请先删除管理员列表对应类型账户'];
                    }

                } else {
                    $data = ['err' => 'id参数错误'];
                }
            }
        } else {
            $data = ['err' => '提交参数错误'];
        }
        return $data;
    }


    public function addhuiyuan()
    {
        $post = input('post.');

        if (!$post['vip_id']) {
            Db::name('user')->where('id', $post['user_id'])->setField('noble_grade', 0);
            Db::name('user_noble')->where(['expire'=>['>', time()]])->update(['expire'=>time()]);
            return ['state' => 1, 'msg' => '操作成功'];
        } else {
            $gradeNoble = Db::name('grade_noble')->find($post['vip_id']);

            $userGrade = UserNoble::get(['user_id' => $post['user_id'], 'grade' => $gradeNoble['grade']]);
            if ($userGrade) {
                UserNoble::update(['id' => $userGrade->id, 'expire' => strtotime($post['time']), 'update_time' => time()]);
            } else {
                UserNoble::create([
                    'user_id' => $post['user_id'],
                    'grade' => $gradeNoble['grade'],
                    'expire' => strtotime($post['time']),
                    'create_time' => time(),
                    'update_time' => time(),
                ]);
            }

            $res = Db::name('user')->where('id', $post['user_id'])->update(['noble_grade' => $gradeNoble['grade'], 'noble_time' => strtotime($post['time'])]);
        }

        if ($res !== false) {
            $result = ['state' => 1, 'msg' => '操作成功'];
        } else {
            $result = ['state' => 0, 'msg' => '操作失败'];
        }
        return $result;
    }

    public function addcar()
    {
        $post = input('post.');

        $car = Db::name('car')->find($post['car_id']);

        $userCar = Db::name('user_car')->where(['car_id' => $post['car_id'], 'user_id' => $post['user_id']])->find();

        if ($userCar) {
            $expire = $userCar['expire'] > time() ? $userCar['expire'] : time();

            $time = $expire + $post['time'] * 86400;

            $res = Db::name('user_car')->where(['id' => $userCar['id']])->update(['expire' => $time, 'update_time' => time()]);
        } else {
            $res = Db::name('user_car')->insert([
                'car_id' => $post['car_id'],
                'user_id' => $post['user_id'],
                'expire' => $post['time'] * 86400 + time(),
                'create_time' => time(),
                'update_time' => time(),
            ]);
        }

        if ($res !== false) {
            $result = ['state' => 1, 'msg' => '操作成功'];
        } else {
            $result = ['state' => 0, 'msg' => '操作失败'];
        }
        return $result;
    }

    public function frozen()
    {
        $post = input('post.');

        $user = Db::name('user')->find($post['user_id']);

        $res = false;
        $time = time();
        $result = false;
        if ($user) {
            $frozen = Db::name('wallet_frozen')->where(['user_id'=>$post['user_id']])->find();
            if($frozen){
                $frozened = $frozen['value'];
                $frozenid = $frozen['id'];
            }else{
                $frozened = 0;
                $frozenid = Db::name('wallet_frozen')->insertGetid(['user_id'=>$post['user_id'], 'create_time' => $time, 'update_time' => $time]);
            }
            if($post['value'] > 0 && $post['value'] < $user['score'] - $frozened){
                UserPunish::inc($user['id'], 'wallet_frozen');
                $res = Db::name('wallet_frozen')->where(['id'=>$frozenid])->update(['value'=>$frozened + $post['value'], 'update_time'=>$time]);
                Db::name('wallet_frozen_records')->insert(['user_id'=>$post['user_id'],'value'=>$post['value'], 'remark'=>$post['remark'], 'time'=>$time]);
            }else{
                $result = ['state' => 0, 'msg' => '超出可冻结数量'];
            }
        }

        if ($res !== false) {
            $result = ['state' => 1, 'msg' => '操作成功'];
        } elseif(!$result) {
            $result = ['state' => 0, 'msg' => '操作失败'];
        }
        return $result;
    }

    public function setDangerTags()
    {
        $post = input('post.');
        $user = Db::name('user')->find($post['user_id']);
        if ($user) {
            Db::name('user')->where(['id'=>$post['user_id']])->setField('danger_tags', $post['value']);
            $result = ['state' => 1, 'msg' => '操作成功'];
        } else {
            $result = ['state' => 0, 'msg' => '操作失败'];
        }
        return $result;
    }
    public function setQuality()
    {
        $post = input('post.');
        $user = Db::name('user')->find($post['user_id']);
        if ($user) {
            Db::name('user')->where(['id'=>$post['user_id']])->setField('quality', $post['value']);
            if($user['quality'] != $post['value']) {
                $admin = Session::get('admin', 'mmjtAdmin');
                $qualitys = ['未检出','低端','一般','优质','超优质'];
                $text = '修改用户质量：'.$qualitys[$user['quality']].'=>'.$qualitys[$post['value']];
                Db::name('admin_logs')->insert(['channel'=>3,'admin'=>$admin['name'],'user_id'=>$post['user_id'],'content'=>$text]);
            }
            $result = ['state' => 1, 'msg' => '操作成功'];
        } else {
            $result = ['state' => 0, 'msg' => '操作失败'];
        }
        return $result;
    }
    public function setJiaoyouLv()
    {
        $post = input('post.');
        $user = Db::name('user')->find($post['user_id']);
        if ($user) {
            Db::name('user')->where(['id'=>$post['user_id']])->setField('jiaoyou_lv', $post['value']);
            if($user['jiaoyou_lv'] != $post['value']) {
                $admin = Session::get('admin', 'mmjtAdmin');
                $jiaoyou_lvs = ['未设置','婚恋','交友','一般','很低'];
                $text = '修改用户交友意愿：'.$jiaoyou_lvs[$user['jiaoyou_lv']].'=>'.$jiaoyou_lvs[$post['value']];
                Db::name('admin_logs')->insert(['channel'=>3,'admin'=>$admin['name'],'user_id'=>$post['user_id'],'content'=>$text]);
            }
            $result = ['state' => 1, 'msg' => '操作成功'];
        } else {
            $result = ['state' => 0, 'msg' => '操作失败'];
        }
        return $result;
    }
    public function setPornoLv()
    {
        $post = input('post.');
        $user = Db::name('user')->find($post['user_id']);
        if ($user) {
            if($user['porno_lv'] != $post['value']) {
                $admin = Session::get('admin', 'mmjtAdmin');
                if ($admin['id']!=1) {
                    if ($post['value'] != 0) return ['state'=>0,'msg'=>'仅允许调整为超优秀'];
                }
                $porno_lvs = ['超优秀','优秀','普通','一般','差'];
                $text = '修改涉黄警报级别：'.$porno_lvs[$user['porno_lv']].'=>'.$porno_lvs[$post['value']];
                Db::name('admin_logs')->insert(['channel'=>3,'admin'=>$admin['name'],'user_id'=>$post['user_id'],'content'=>$text]);
            }
            Db::name('user')->where(['id'=>$post['user_id']])->setField('porno_lv', $post['value']);
            $result = ['state' => 1, 'msg' => '操作成功'];
        } else {
            $result = ['state' => 0, 'msg' => '操作失败'];
        }
        return $result;
    }

    public function clearUnReplyChatList()
    {
        $start_time = strtotime('-14 day');

        $where = ['user_time' => ['lt', $start_time], 'user_first' => 1];
        $whereor = ['another_time' => ['lt', $start_time], 'another_first' => 1];
        Db::name('chat_lists')->where($where)->whereOr(function ($query) use ($whereor) {
            $query->where($whereor);
        })->delete();
    }

    public function clearScore()
    {
        ini_set("memory_limit", '2048M');
        if(Cache::get('remove_wait_clearScore')){
            return json(['err'=>'距离上次大量清理数据时间较近，请等待10秒后再试']);
        }
        $del = false;
        $list = Db::name('yaoqing_records')->whereTime('time', '<', '-7 days')->limit(20000)->column('id');
        if(sizeof($list)){
            $del = Db::name('yaoqing_records')->where(['id'=>['in', $list]])->delete();
        }else{
            return json(['err'=>'暂未数据可清理']);
        }

        if($del){
            $len = sizeof($list);
            if($len > 5000){
                Cache::set('remove_wait_clearScore', 1, 10);
            }else{
                Cache::rm('remove_wait_clearScore');
            }
            return json(['ret'=>'已清理' . $len . '条']);
        }else{
            Cache::rm('remove_wait_clearScore');
            return json(['err'=>'暂未数据可清理']);
        }
    }

    public function clearVolley()
    {
        ini_set("memory_limit", '2048M');
        if(Cache::get('remove_wait_clearScore')){
            return json(['err'=>'距离上次大量清理数据时间较近，请等待10秒后再试']);
        }
        $del = false;
        $list = Db::name('volley_desc')->whereTime('time', '<', '-7 days')->limit(20000)->column('id');
        if(sizeof($list)){
            $del = Db::name('volley_desc')->where(['id'=>['in', $list]])->delete();
        }else{
            return json(['err'=>'暂未数据可清理']);
        }

        if($del){
            $len = sizeof($list);
            if($len > 5000){
                Cache::set('remove_wait_clearScore', 1, 10);
            }else{
                Cache::rm('remove_wait_clearScore');
            }
            return json(['ret'=>'已清理' . $len . '条']);
        }else{
            Cache::rm('remove_wait_clearScore');
            return json(['err'=>'暂未数据可清理']);
        }
    }

    public function clearHiAudio()
    {
        $data = Db::name('privatechat_greet')->where(['channel'=>1])->order('id asc')->select();
        foreach ($data as $key => $value) {
            try {
                $file = file_get_contents(_ossUrl().$value['content']);
            } catch (\Exception $e) {
                Db::name('privatechat_greet')->where(['id'=>$value['id']])->delete();
            }
        }
    }


    public function clearWithdraw()
    {
        ini_set("memory_limit", '2048M');
        if(Cache::get('remove_wait_clearScore')){
            return json(['err'=>'距离上次大量清理数据时间较近，请等待10秒后再试']);
        }
        $del = false;
        $list = Db::name('withdraw')->whereTime('create_time', '<', '-7 days')->limit(20000)->column('id');
        if(sizeof($list)){
            $del = Db::name('withdraw')->where(['id'=>['in', $list]])->delete();
        }else{
            return json(['err'=>'暂未数据可清理']);
        }

        if($del){
            $len = sizeof($list);
            if($len > 5000){
                Cache::set('remove_wait_clearScore', 1, 10);
            }else{
                Cache::rm('remove_wait_clearScore');
            }
            return json(['ret'=>'已清理' . $len . '条']);
        }else{
            Cache::rm('remove_wait_clearScore');
            return json(['err'=>'暂未数据可清理']);
        }
    }
    public function clearWithdrawMerge()
    {
        ini_set("memory_limit", '2048M');
        if(Cache::get('remove_wait_clearScore')){
            return json(['err'=>'距离上次大量清理数据时间较近，请等待10秒后再试']);
        }
        $del = false;
        $list = Db::name('withdraw_merge')->whereTime('create_time', '<', '-7 days')->limit(20000)->column('id');
        if(sizeof($list)){
            $del = Db::name('withdraw_merge')->where(['id'=>['in', $list]])->delete();
        }else{
            return json(['err'=>'暂未数据可清理']);
        }

        if($del){
            $len = sizeof($list);
            if($len > 5000){
                Cache::set('remove_wait_clearScore', 1, 10);
            }else{
                Cache::rm('remove_wait_clearScore');
            }
            return json(['ret'=>'已清理' . $len . '条']);
        }else{
            Cache::rm('remove_wait_clearScore');
            return json(['err'=>'暂未数据可清理']);
        }
    }

    public function clearZhuxiaoChatList()
    {
        ini_set("memory_limit", '2048M');
        if(Cache::get('remove_wait_clearScore')){
            return json(['err'=>'距离上次大量清理数据时间较近，请等待10秒后再试']);
        }
        $del = false;
        $sql = "select id from chat_lists where user_id in (select id from user where delete_time>0) or another_id in (select id from user where delete_time>0) order by id asc limit 20000";
        $list = Db::query($sql);
        // var_dump($list);exit;
        if(sizeof($list)){
            $del = Db::name('chat_lists')->where(['id'=>['in', array_column($list, 'id')]])->delete();
        }else{
            return json(['err'=>'暂未数据可清理']);
        }
        if($del){
            $len = sizeof($list);
            if($len > 5000){
                Cache::set('remove_wait_clearScore', 1, 10);
            }else{
                Cache::rm('remove_wait_clearScore');
            }
            return json(['ret'=>'已清理' . $len . '条']);
        }else{
            Cache::rm('remove_wait_clearScore');
            return json(['err'=>'暂未数据可清理']);
        }
    }

    public function clearYoukeRepeat()
    {
        if(Cache::get('remove_wait_clearScore')){
            return json(['err'=>'距离上次大量清理数据时间较近，请等待10秒后再试']);
        }
        $userids = Db::name('user_repeat_check')->alias('c')->join('user u', 'c.user_id=u.id')->where(['u.reg'=>0])->limit(20000)->column('c.user_id');

        $len = sizeof($userids);
        if($len){
            $del = Db::name('user_repeat_check')->where(['user_id'=>['in', $userids]])->delete();
        }else{
            return json(['err'=>'暂未数据可清理']);
        }
        if($del){
            if($len > 5000){
                Cache::set('remove_wait_clearScore', 1, 10);
            }else{
                Cache::rm('remove_wait_clearScore');
            }
            return json(['ret'=>'已清理' . $len . '条']);
        }else{
            Cache::rm('remove_wait_clearScore');
            return json(['err'=>'暂未数据可清理']);
        }
    }

    public function clearYoukeAccount()
    {
        $cachekey = 'clearYoukeAccount';
        $last_id = cache($cachekey);
        $last_id = $last_id ?: 0;
        $threeday = date('Y-m-d', strtotime('-3 day'));
        $yks = Db::name('user')->where(['id'=>['>', $last_id],'reg'=>0])->where("last_login_datetime <= '$threeday'")->field('id,device_id')->limit(1000)->select();
        $device_ids = Db::name('user')->where("reg > 0 and device_id is not null and device_id != ''")->cache(3600)->fetchSql(false)->column('device_id');
        // print_r($device_ids);exit;
        $rms = [];
        $devs = [];
        foreach ($yks as $key => $value) {
            $last_id = $value['id'];
            if (in_array($value['device_id'], $device_ids)) continue;
            $rms[] = $value['id'];
            $devs[] = $value['device_id'];
        }

        if (sizeof($rms) <= 0) {
            cache($cachekey, $last_id, 86400);
            echo $last_id;
            return '';
        }

        $where = [];
        foreach ($devs as $key => $value) {
            $where[] = "device_ids like '%".$value."%'";
        }
        $userRepeatChecks = Db::name('user_repeat_check')->where(implode(' or ', $where))->field('user_id,device_ids')->fetchSql(false)->select();

        foreach ($devs as $key => $value) {
            foreach ($userRepeatChecks as $k => $v) {
                $devices = explode(',', $v['device_ids']);
                $idx = array_search($value, $devices);
                if ($idx !== false) {
                    unset($devices[$idx]);
                    $devices = implode(',', $devices);
                    Db::name('user_repeat_check')->where(['user_id'=>$v['user_id']])->update(['device_ids'=>$devices]);
                }
            }
        }

        Db::name('user')->where(['id'=>['in', $rms], 'reg'=>0])->delete();

        cache($cachekey, $last_id, 86400);
        echo $last_id;
        echo '删除'.sizeof($rms).'个';
    }



    public function clearShenheRecords()
    {
        ini_set("memory_limit", '2048M');
        if(Cache::get('remove_wait_clearScore')){
            return json(['err'=>'距离上次大量清理数据时间较近，请等待10秒后再试']);
        }
        $del = false;
        $list = Db::name('shenhe_task_records')->whereTime('create_time', '<', '-60 days')->limit(20000)->column('id');
        if(sizeof($list)){
            $del = Db::name('shenhe_task_records')->where(['id'=>['in', $list]])->delete();
        }else{
            return json(['err'=>'暂未数据可清理']);
        }

        if($del){
            $len = sizeof($list);
            if($len > 5000){
                Cache::set('remove_wait_clearScore', 1, 10);
            }else{
                Cache::rm('remove_wait_clearScore');
            }
            return json(['ret'=>'已清理' . $len . '条']);
        }else{
            Cache::rm('remove_wait_clearScore');
            return json(['err'=>'暂未数据可清理']);
        }
    }

    public function clearDeviceids()
    {
        $cachekey = 'clearDeviceids';
        $last_id = cache($cachekey);
        $last_id = $last_id ?: 0;
        $repeats = Db::name('user_repeat_check')->where(['user_id'=>['>', $last_id]])->field('user_id,device_ids')->limit(100)->order('user_id asc')->select();
        $saveAll = [];

        foreach ($repeats as $key => $value) {
            $last_id = $value['user_id'];
            $device_ids = explode(',', $value['device_ids']);
            if (sizeof($device_ids) < 10) continue;
            $unset = [];
            foreach ($device_ids as $k => $v) {
                $has = Db::name('user_device_records')->where(['user_id'=>['<>', $value['user_id']], 'device_id'=>$v])->find();
                if ($has) continue;
                $has = Db::name('user')->where(['device_id'=>$v])->find();
                if ($has) continue;
                $has = Db::name('user_repeat_check')->where(['user_id'=>['<>', $value['user_id']], 'device_ids'=>['like', "%$v%"]])->find();
                if ($has) continue;

                $unset[] = $v;
            }
            if (sizeof($unset)) {
                $newDevs = array_diff($device_ids, $unset);

                if (empty($newDevs)) {
                    $did = Db::name('user')->where(['id'=>$value['user_id']])->value('device_id');
                    if ($did) {
                        $newDevs[] = $did;
                    }
                }

                // var_dump($value['user_id']);
                // echo "<br />";
                // echo "<br />";
                // var_dump($device_ids);
                // echo "<br />";
                // echo "<br />";
                // var_dump($unset);
                // echo "<br />";
                // echo "<br />";
                // var_dump($newDevs);exit;

                // Db::name('user_repeat_check')->where(['user_id'=>$value['user_id']])->update(['device_ids'=>implode(',', $newDevs)]);
                $saveAll[] = ['user_id'=>$value['user_id'], 'device_ids'=>implode(',', $newDevs)];
            }
        }

        $len = sizeof($saveAll);
        if ($len) {
            (new \app\api\model\UserRepeatCheck)->saveAll($saveAll);
        }
        
        cache($cachekey, $last_id, 86400);
        echo $last_id;
    }

    public function setPages()
    {
        $session_id = session_id();
        $pages = input('pages/d', config('paginate.list_rows'));
        $action = input('action');
        cache('pages:'.$action.':'.$session_id, $pages, 86400 * 7);
        return ['ret'=>''];
    }


    public function auditAudio()
    {
        $where = [];

        $data = Db::name('admin_audit_audio')
            ->where($where)
            ->select();

        $type = db('admin_audit_type')->column('name','id');

        foreach ($data as &$value) {
            $value['cate'] = $type[$value['cid']] ?? '';
        }

        $this->assign('data', $data);

        return $this->fetch();
    }

    public function addAuditAudio()
    {
        $id = input("id");

        if (request()->isAjax()) {
            $post = input('post.');

            $res = Db::name('admin_audit_audio')->where('id', $id)->update($post);
            if ($res) {
                $data = ['ret' => '修改成功'];
            } else {
                $data = ['err' => '修改失败'];
            }
        } else {
            $type = db('admin_audit_type')->select();
            if ($id) {
                $name = Db::name('admin_audit_audio')->find($id);

                if ($name) {
                    $this->assign('name', $name);
                } else {
                    return ['err' => 'id参数错误'];
                }
            }
            $this->assign('type', $type);
            $data = $this->fetch();
        }

        return $data;
    }
}